import tkinter as tk
import random
import time

class SnakeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("贪吃蛇游戏")
        self.master.resizable(False, False)
        self.master.bind("<Key>", self.key_press)
        
        # 游戏参数
        self.width = 600
        self.height = 400
        self.cell_size = 20
        self.speed = 150  # 毫秒
        
        # 创建画布
        self.canvas = tk.Canvas(self.master, width=self.width, height=self.height, bg="black")
        self.canvas.pack()
        
        # 初始化蛇
        self.snake = [(5, 5), (4, 5), (3, 5)]
        self.direction = "Right"
        self.next_direction = "Right"
        
        # 食物
        self.food = self.create_food()
        
        # 游戏状态
        self.game_over = False
        self.score = 0
        
        # 显示分数
        self.score_text = self.canvas.create_text(
            50, 10, text=f"分数: {self.score}", fill="white", font=("Arial", 12)
        )
        
        # 开始游戏
        self.update()
    
    def create_food(self):
        """在随机位置创建食物"""
        while True:
            x = random.randint(0, (self.width // self.cell_size) - 1)
            y = random.randint(0, (self.height // self.cell_size) - 1)
            if (x, y) not in self.snake:
                return (x, y)
    
    def draw_snake(self):
        """绘制蛇"""
        self.canvas.delete("snake")
        for x, y in self.snake:
            self.canvas.create_rectangle(
                x * self.cell_size, y * self.cell_size,
                (x + 1) * self.cell_size, (y + 1) * self.cell_size,
                fill="green", tag="snake"
            )
    
    def draw_food(self):
        """绘制食物"""
        self.canvas.delete("food")
        x, y = self.food
        self.canvas.create_oval(
            x * self.cell_size, y * self.cell_size,
            (x + 1) * self.cell_size, (y + 1) * self.cell_size,
            fill="red", tag="food"
        )
    
    def key_press(self, event):
        """处理键盘输入"""
        key = event.keysym
        if key in ["Up", "Down", "Left", "Right"]:
            # 防止直接反向移动
            if (key == "Up" and self.direction != "Down") or \
               (key == "Down" and self.direction != "Up") or \
               (key == "Left" and self.direction != "Right") or \
               (key == "Right" and self.direction != "Left"):
                self.next_direction = key
    
    def move_snake(self):
        """移动蛇"""
        head_x, head_y = self.snake[0]
        
        if self.next_direction == "Up":
            new_head = (head_x, head_y - 1)
        elif self.next_direction == "Down":
            new_head = (head_x, head_y + 1)
        elif self.next_direction == "Left":
            new_head = (head_x - 1, head_y)
        elif self.next_direction == "Right":
            new_head = (head_x + 1, head_y)
        
        self.direction = self.next_direction
        
        # 检查是否撞墙或撞到自己
        if (new_head in self.snake or
            new_head[0] < 0 or new_head[0] >= self.width // self.cell_size or
            new_head[1] < 0 or new_head[1] >= self.height // self.cell_size):
            self.game_over = True
            return
        
        self.snake.insert(0, new_head)
        
        # 检查是否吃到食物
        if new_head == self.food:
            self.score += 10
            self.canvas.itemconfig(self.score_text, text=f"分数: {self.score}")
            self.food = self.create_food()
        else:
            self.snake.pop()
    
    def update(self):
        """更新游戏状态"""
        if not self.game_over:
            self.move_snake()
            self.draw_snake()
            self.draw_food()
            self.master.after(self.speed, self.update)
        else:
            self.canvas.create_text(
                self.width // 2, self.height // 2,
                text="游戏结束!", fill="white", font=("Arial", 24), tag="gameover"
            )
            self.canvas.create_text(
                self.width // 2, self.height // 2 + 30,
                text=f"最终分数: {self.score}", fill="white", font=("Arial", 16), tag="gameover"
            )
            self.canvas.create_text(
                self.width // 2, self.height // 2 + 60,
                text="按空格键重新开始", fill="white", font=("Arial", 12), tag="gameover"
            )
            self.master.bind("<space>", self.restart_game)
    
    def restart_game(self, event=None):
        """重新开始游戏"""
        self.canvas.delete("gameover")
        self.snake = [(5, 5), (4, 5), (3, 5)]
        self.direction = "Right"
        self.next_direction = "Right"
        self.food = self.create_food()
        self.game_over = False
        self.score = 0
        self.canvas.itemconfig(self.score_text, text=f"分数: {self.score}")
        self.master.unbind("<space>")
        self.update()

if __name__ == "__main":
    # 创建主窗口并启动游戏
    root = tk.Tk()
    game = SnakeGame(root)
    root.mainloop()